<template>
    <div class="auction-detail" v-loading="loading">
        <div v-if="auction" class="detail-container">
            <!-- 拍卖品基本信息区 -->
            <div class="basic-info">
                <div class="left-section">
                    <div class="image-container">
                        <img :src="auction.image || 'https://via.placeholder.com/500x400'" alt="拍卖品图片" />
                        <div class="auction-status" :class="getStatusClass(auction.status)">
                            {{ getStatusText(auction.status) }}
                        </div>
                    </div>
                </div>

                <div class="right-section">
                    <h1 class="title">{{ auction.title }}</h1>
                    <div class="auction-meta">
                        <div class="meta-item">
                            <span class="label">拍卖编号:</span>
                            <span>{{ auction.id }}</span>
                        </div>
                        <div class="meta-item">
                            <span class="label">卖家:</span>
                            <span>{{ auction.sellerName }}</span>
                        </div>
                        <div class="meta-item">
                            <span class="label">发布时间:</span>
                            <span>{{ formatDate(auction.createTime) }}</span>
                        </div>
                        <div class="meta-item">
                            <span class="label">拍卖状态:</span>
                            <span :class="getStatusClass(auction.status)">{{ getStatusText(auction.status) }}</span>
                        </div>
                    </div>

                    <div class="price-info">
                        <div class="price-item">
                            <span class="label">起拍价:</span>
                            <span class="price">￥{{ auction.startPrice }}</span>
                        </div>
                        <div class="price-item">
                            <span class="label">当前价:</span>
                            <span class="price highlight">￥{{ auction.currentPrice || auction.startPrice }}</span>
                        </div>
                        <div class="price-item">
                            <span class="label">加价幅度:</span>
                            <span>￥{{ auction.priceIncrement }}</span>
                        </div>
                    </div>

                    <div class="time-info">
                        <div class="time-item">
                            <span class="label">开始时间:</span>
                            <span>{{ formatDate(auction.startTime) }}</span>
                        </div>
                        <div class="time-item">
                            <span class="label">结束时间:</span>
                            <span>{{ formatDate(auction.endTime) }}</span>
                        </div>
                        <div class="time-item" v-if="auction.status === 'ACTIVE'">
                            <span class="label">剩余时间:</span>
                            <span class="countdown">{{ remainingTime }}</span>
                        </div>
                    </div>

                    <!-- 竞价表单 -->
                    <div class="bid-form" v-if="auction.status === 'ACTIVE'">
                        <div class="bid-controls">
                            <span class="label">出价金额:</span>
                            <el-input-number v-model="bidAmount" :min="minBidAmount" :step="auction.priceIncrement || 1"
                                :precision="2" size="large" class="bid-input" />
                            <el-button type="primary" size="large" @click="submitBid">立即竞价</el-button>
                        </div>
                        <div class="bid-tips">
                            <p>当前最低可出价: ￥{{ minBidAmount }}</p>
                            <p>已有 {{ bidList.length }} 人参与竞拍</p>
                        </div>
                    </div>

                    <!-- 已结束或未开始提示 -->
                    <div class="auction-notice" v-else>
                        <template v-if="auction.status === 'PENDING'">
                            <el-alert title="拍卖尚未开始" type="info" :closable="false">
                                <template #default>
                                    拍卖将于 {{ formatDate(auction.startTime) }} 开始，请届时参与。
                                </template>
                            </el-alert>
                        </template>
                        <template v-else-if="auction.status === 'FINISHED'">
                            <el-alert title="拍卖已结束" type="warning" :closable="false">
                                <template #default>
                                    该拍卖已于 {{ formatDate(auction.endTime) }} 结束。
                                    <span v-if="auction.winnerId">
                                        <br>成交价: ￥{{ auction.finalPrice || auction.currentPrice }}
                                    </span>
                                </template>
                            </el-alert>
                        </template>
                        <template v-else-if="auction.status === 'CANCELLED'">
                            <el-alert title="拍卖已取消" type="error" :closable="false">
                                <template #default>
                                    该拍卖已被卖家取消。
                                </template>
                            </el-alert>
                        </template>
                    </div>
                </div>
            </div>

            <!-- 详情和竞价记录标签页 -->
            <div class="detail-tabs">
                <el-tabs v-model="activeTab">
                    <el-tab-pane label="拍品详情" name="description">
                        <div class="description" v-html="auction.description || '暂无详细描述'"></div>
                    </el-tab-pane>
                    <el-tab-pane label="竞价记录" name="bids">
                        <div class="bid-history">
                            <el-table :data="bidList" style="width: 100%" v-loading="bidLoading">
                                <el-table-column prop="username" label="用户名">
                                    <template #default="scope">
                                        {{ scope.row.username || '未知' }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="bidPrice" label="出价金额">
                                    <template #default="scope">
                                        ￥{{ scope.row.bidPrice }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="bidTime" label="出价时间">
                                    <template #default="scope">
                                        {{ formatDate(scope.row.bidTime) }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="状态">
                                    <template #default="scope">
                                        <el-tag :type="scope.row.isHighest ? 'success' : 'info'" size="small">
                                            {{ scope.row.isHighest ? '最高出价' : '出局' }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-empty v-if="bidList.length === 0 && !bidLoading" description="暂无竞价记录" />
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
        <el-empty v-else-if="!loading" description="未找到拍卖品信息"></el-empty>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAuctionDetail } from '@/api/auction'
import { getUserAuctionBids, submitBid as submitUserBid } from '@/api/bid'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const bidLoading = ref(false)
const auction = ref(null)
const bidList = ref([])
const activeTab = ref('description')
const remainingTime = ref('计算中...')
const bidAmount = ref(0)
const timer = ref(null)

// 计算最低可出价金额
const minBidAmount = computed(() => {
    if (!auction.value) return 0
    const currentPrice = auction.value.currentPrice || auction.value.startPrice
    const increment = auction.value.priceIncrement || 1
    return parseFloat((currentPrice + increment).toFixed(2))
})

// 获取拍卖详情
const fetchAuctionDetail = async () => {
    loading.value = true
    try {
        const id = route.params.id
        const res = await getAuctionDetail(id)

        if (res) {
            auction.value = res
            // 设置出价金额为最低可出价金额
            bidAmount.value = minBidAmount.value

            // 如果拍卖活跃，开始倒计时
            if (res.status === 'ACTIVE') {
                startCountdown()
            }

            // 同时获取竞价记录
            fetchBidHistory()
        } else {
            ElMessage.error('获取拍卖详情失败')
        }
    } catch (error) {
        console.error('获取拍卖详情错误:', error)
        ElMessage.error('获取拍卖详情失败，请稍后再试')
    } finally {
        loading.value = false
    }
}

// 获取竞价记录
const fetchBidHistory = async () => {
    if (!auction.value) return

    bidLoading.value = true
    try {
        const res = await getUserAuctionBids(auction.value.id)

        if (res && res.data && Array.isArray(res.data)) {
            // 标记最高出价
            const sortedBids = [...res.data].sort((a, b) => b.bidPrice - a.bidPrice)
            bidList.value = sortedBids.map((bid, index) => ({
                ...bid,
                isHighest: index === 0
            }))
        } else {
            bidList.value = []
        }
    } catch (error) {
        console.error('获取竞价记录错误:', error)
        ElMessage.error('获取竞价记录失败')
    } finally {
        bidLoading.value = false
    }
}

// 提交竞价
const submitBid = async () => {
    // 防止重复提交
    if (bidLoading.value) return;
    bidLoading.value = true;
    // 检查是否登录
    const token = localStorage.getItem('userToken');
    if (!token) {
        ElMessageBox.confirm(
            '您需要登录后才能参与竞拍',
            '提示',
            {
                confirmButtonText: '去登录',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            router.push('/login');
        }).catch(() => { });
        bidLoading.value = false;
        return;
    }
    // 检查竞价金额
    if (bidAmount.value < minBidAmount.value) {
        ElMessage.warning(`出价不能低于最低出价金额 ￥${minBidAmount.value}`);
        bidAmount.value = minBidAmount.value;
        bidLoading.value = false;
        return;
    }
    try {
        const bidData = {
            auctionId: auction.value.id,
            bidPrice: bidAmount.value
        };
        const res = await submitUserBid(bidData);
        if (res) {
            ElMessage.success('竞价成功!');
            // 刷新拍卖详情和竞价记录
            fetchAuctionDetail();
        }
    } catch (error) {
        console.error('竞价失败:', error);
        const errorMsg = error.response?.data?.message || '竞价失败，请稍后再试';
        ElMessage.error(errorMsg);
    } finally {
        bidLoading.value = false;
    }
};
// 获取状态文本
const getStatusText = (status) => {
    const statusMap = {
        'PENDING': '即将开始',
        'ACTIVE': '正在进行',
        'FINISHED': '已结束',
        'CANCELLED': '已取消'
    }
    return statusMap[status] || '未知'
}

// 获取状态样式类
const getStatusClass = (status) => {
    const statusMap = {
        'PENDING': 'status-pending',
        'ACTIVE': 'status-active',
        'FINISHED': 'status-finished',
        'CANCELLED': 'status-cancelled'
    }
    return statusMap[status] || ''
}

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '未知'
    const date = new Date(dateStr)
    return date.toLocaleString()
}

// 开始倒计时
const startCountdown = () => {
    if (timer.value) clearInterval(timer.value)

    timer.value = setInterval(() => {
        if (!auction.value || !auction.value.endTime) {
            clearInterval(timer.value)
            return
        }

        const now = new Date().getTime()
        const end = new Date(auction.value.endTime).getTime()
        const diff = end - now

        if (diff <= 0) {
            remainingTime.value = '已结束'
            clearInterval(timer.value)
            // 刷新竞拍状态
            fetchAuctionDetail()
            return
        }

        // 计算天、时、分、秒
        const days = Math.floor(diff / (1000 * 60 * 60 * 24))
        const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
        const seconds = Math.floor((diff % (1000 * 60)) / 1000)

        remainingTime.value = `${days}天 ${hours}时 ${minutes}分 ${seconds}秒`
    }, 1000)
}

onMounted(() => {
    fetchAuctionDetail()
})

onUnmounted(() => {
    if (timer.value) {
        clearInterval(timer.value)
    }
})
</script>

<style scoped>
.auction-detail {
    padding: 20px 0;
}

.detail-container {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.basic-info {
    display: flex;
    padding: 30px;
}

@media (max-width: 768px) {
    .basic-info {
        flex-direction: column;
    }
}

.left-section {
    flex: 0 0 45%;
    max-width: 500px;
    margin-right: 30px;
}

.image-container {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.image-container img {
    width: 100%;
    height: 400px;
    object-fit: cover;
}

.auction-status {
    position: absolute;
    top: 15px;
    right: 15px;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: bold;
    color: #fff;
}

.status-active {
    background-color: #67c23a;
}

.status-pending {
    background-color: #909399;
}

.status-finished {
    background-color: #e6a23c;
}

.status-cancelled {
    background-color: #f56c6c;
}

.right-section {
    flex: 1;
}

.title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #303133;
    line-height: 1.4;
}

.auction-meta {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
    margin-bottom: 20px;
}

.meta-item,
.price-item,
.time-item {
    display: flex;
    align-items: center;
}

.price-info,
.time-info {
    margin-bottom: 25px;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
}

.label {
    color: #909399;
    margin-right: 8px;
    font-size: 14px;
}

.price {
    font-size: 16px;
    font-weight: bold;
}

.highlight {
    color: #f56c6c;
    font-size: 20px;
}

.countdown {
    color: #e6a23c;
    font-weight: bold;
}

.bid-form {
    margin-top: 30px;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.bid-controls {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.bid-input {
    margin: 0 15px;
}

.bid-tips {
    font-size: 13px;
    color: #606266;
}

.auction-notice {
    margin-top: 30px;
}

.detail-tabs {
    padding: 20px 30px 40px;
}

.description {
    padding: 20px 0;
    line-height: 1.8;
}
</style>